package net;

import net.message.processor.MessageProcessor;
import net.message.processor.MessageWorker;
import net.message.MessageType;
import net.receiving.IncomingMessageFactory;

import util.Config;

import java.net.InetAddress;

public class Receiver extends StoppableWorker {

    private final MessageWorker messageWorker;

    private final IncomingMessageFactory factory;

    public Receiver(IncomingMessageFactory factory,
                    MessageProcessor processor) {
        this.factory = factory;
        messageWorker = new MessageWorker(processor);
        new Thread(messageWorker).start();
    }

    @Override
    public void work() {
        IncomingMessage im;
        while (true) {
            im = factory.receive();
            if (!im.sourceAddress.getName().equals(Config.getInstance().getName())) break;
            if (im.message.getType().equals(MessageType.HELLO_RESPONSE)) {
                System.out.println("Error: there is other client <" + im.sourceAddress.getIp() +
                        "> with name <" + im.sourceAddress.getName() + ">!!!");
                System.exit(239);
            } else if (im.message.getType().equals(MessageType.HELLO_REQUEST)) {
                try {
                    if (!im.sourceAddress.getIp().getHostAddress().equals(InetAddress.getLocalHost().getHostAddress())) {
                        break;
                    }
                } catch (java.net.UnknownHostException e) {
                    throw new RuntimeException(e);
                }
            }

        }
        System.out.println("Received " + im.message.getType() + " from " + im.sourceAddress.getName() + "   " + im.sourceAddress.getIp());
        messageWorker.addMessage(im);
    }

}